"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _forEach = _interopRequireDefault(require("./forEach"));
/**
 * 前序遍历，将树扁平化成一维数组
 * 每个返回节点会清空子节点，并设置额外的 [levelKey], [parentKey] 属性，但不改变原始数据
 * @param treeNodes
 * @param options
 * @returns
 */
const toArray = (treeNodes, options) => {
  const {
    uniqueKey = 'key',
    levelKey = 'level',
    childrenKey = 'children',
    parentKey = 'parentKey',
    level = 0
  } = options ?? {};
  const result = [];
  (0, _forEach.default)(treeNodes, (treeNode, {
    parent,
    level
  }) => {
    if (!(uniqueKey in treeNode)) {
      throw new Error('please check unique key!');
    }
    const convertedNode = {
      ...treeNode,
      [levelKey]: level,
      [parentKey]: parent?.[uniqueKey],
      [childrenKey]: undefined
    };
    delete convertedNode[childrenKey];
    result.push(convertedNode);
  }, {
    childrenKey,
    order: 'dlr',
    level
  });
  return result;
};
var _default = exports.default = toArray;